
source("./hg_rselenium_funs.R", encoding = "UTF-8")
use("XML", "xml2", "RCurl", 
    "rvest", "stringr", "readxl", 
    "tidyverse", "scales", "lubridate", 
    "showtext", "RSelenium", "rvest")

system("java -jar C:/krupSoftware/bin/selenium-server-standalone-3.7.1.jar",
       wait = FALSE, invisible = FALSE
       )
system("java -jar C:/krupSoftware/bin/selenium-server-standalone-3.13.0.jar",
       wait = FALSE, invisible = FALSE
)

remdr <- remoteDriver(browserName = "phantomjs")

remdr

hg_rs_get_sessions_id(remdr)
hg_rs_close(remdr)
hg_rs_open(remdr)
remdr$errorDetails()
remdr$open()
### 

keywords = c("体温计", "暖奶器", "吸奶器", "奶瓶", "爬行垫", "血压计", "血氧仪")
randomi = round(runif(1, 1, length(keywords)))
keyword = keywords[randomi]
keyword

# urls = hg_rs_jd_search_n_pages_urls(remdr, keyword , n_pages = 2)
filename = paste0("c:/Users/krup/Documents/temp/", Sys.Date(), ".csv")
products = rsjd::hg_rs_jd_products(remdr, keyword, filename,
                             n_pages = 1, n_products = 30)
products


config <- new.env() # for package-level global variables

# function to extract Selenium driver (for development)
#' @export
get_driver <- function() {
  config$driver
}

# function to set Selenium driver (for development)
#' @export
set_driver <- function(driver) {
  config$driver <- driver
}

get_session <- function () {
  tryCatch({
    suppressMessages({
      return(config$driver$getSession())
    })
  },
  error = function(e) {
    list()
  })
}

set_driver(remdr)
config$driver$open()
get_session()






i = 0
lapply(1:10, function(w) {
  i <<- i + 1
  print(i)
})

open_browser("http://www.baidu.com")
require(stringi)

#' @export
open_browser <- function (url, browser = "firefox") {
  
  if (missing(url) || !stri_startswith_fixed(url[1], 'http')) stop('url must be a valid URL')
  browser <- match.arg(browser)
  
  # temporary file
  if (.Platform$OS.type == 'windows') {
    config$dir_temp <- paste(tempdir(), "download", sep = '\\')
  } else {
    config$dir_temp <- paste(tempdir(), "download", sep = '/')
  }
  if (!dir.exists(config$dir_temp)) {
    dir.create(config$dir_temp)
  }
  
  # data file
  config$dir_data <- getwd()
  
  if (!length(get_session())) {
    # assign global variable
    config$driver <- remoteDriver(browserName = browser,
                                  extraCapabilities = get_prefs(browser), port=4444)
    config$driver$open(silent = TRUE)
    print_log("Opening browser")
    config$driver$navigate(url[1])
  } else {
    print_log("Browser is already open:", paste0('"', config$driver$getTitle()[[1]], '"'))
  }
}







